package com.example.teaching_server.entity;

import jakarta.persistence.*;
import jakarta.validation.constraints.NotBlank;
import lombok.*;
import org.hibernate.annotations.CreationTimestamp;
import org.hibernate.annotations.UpdateTimestamp;
import com.fasterxml.jackson.annotation.JsonFormat;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

/**
 * 班级实体类
 */
@Getter
@Setter
@ToString(exclude = {"grade", "teachers", "teacherClasses"})
@EqualsAndHashCode(of = "id")
@Entity
@Builder
@NoArgsConstructor
@AllArgsConstructor
@Table(name = "classes")
public class ClassEntity {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "class_id")
    private Long id;

    @Column(name = "class_name", nullable = false)
    @NotBlank(message = "班级名称不能为空")
    private String className;

    @Column(name = "head_teacher")
    private String headTeacher;

    @Column(name = "student_count")
    @Builder.Default
    private Integer studentCount = 0;

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "grade_id")
    private Grade grade;

    @ManyToMany
    @JoinTable(
            name = "teacher_class",
            joinColumns = @JoinColumn(name = "class_id"),
            inverseJoinColumns = @JoinColumn(name = "teacher_id")
    )
    @Builder.Default
    private List<TeacherEntity> teachers = new ArrayList<>();

    @OneToMany(mappedBy = "classEntity")
    @Builder.Default
    private List<TeacherClass> teacherClasses = new ArrayList<>();

    // 保持原有的getter方法名称以兼容现有代码
    public Long getClassId() {
        return id;
    }

    public void setClassId(Long classId) {
        this.id = classId;
    }

    @Transient
    public String getGradeLevel() {
        return grade != null ? grade.getGradeName() : null;
    }

    @Transient
    public Long getGradeId() {
        return grade != null ? grade.getGradeId() : null;
    }

    @Transient
    public String getDisplayName() {
        if (grade != null && grade.getGradeName() != null) {
            return grade.getGradeName() + className;
        }
        return className;
    }

    @Transient
    public boolean hasHeadTeacher() {
        return headTeacher != null && !headTeacher.trim().isEmpty();
    }
}
